<?php
/**
 * 患者管理
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含函数文件
require_once '../includes/functions.php';

// 检查用户是否已登录并具有管理员权限
if (!isLoggedIn() || !hasRole('admin')) {
    $_SESSION['error_msg'] = '您无权访问该页面';
    redirect('../login.php');
}

// 处理患者操作
$success = '';
$error = '';

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10; // 每页显示的记录数
$offset = ($page - 1) * $limit;

// 获取患者总数
$count_sql = "SELECT COUNT(*) as total FROM patients";
$count_result = $conn->query($count_sql);
$total_records = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $limit);

// 获取当前页的患者数据
$patients = [];
$sql = "SELECT p.*, u.username, u.email, u.role, u.created_at 
        FROM patients p 
        LEFT JOIN users u ON p.user_id = u.id 
        ORDER BY p.id DESC LIMIT $offset, $limit";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $patients[] = $row;
    }
}

// 如果是编辑请求，获取患者信息
$edit_patient = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $patient_id = (int)$_GET['edit'];
    $sql = "SELECT p.*, u.username, u.email 
            FROM patients p 
            LEFT JOIN users u ON p.user_id = u.id 
            WHERE p.id = $patient_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $edit_patient = $result->fetch_assoc();
    }
}

// 处理删除患者请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $patient_id = (int)$_GET['delete'];
    
    // 开始事务
    $conn->begin_transaction();
    
    try {
        // 获取患者的用户ID
        $sql = "SELECT user_id FROM patients WHERE id = $patient_id";
        $result = $conn->query($sql);
        
        if ($result && $result->num_rows > 0) {
            $patient = $result->fetch_assoc();
            $user_id = $patient['user_id'];
            
            // 删除患者相关记录
            // 1. 删除预约记录
            $sql = "DELETE FROM appointments WHERE patient_id = $patient_id";
            $conn->query($sql);
            
            // 2. 删除医疗记录
            $sql = "DELETE FROM medical_records WHERE patient_id = $patient_id";
            $conn->query($sql);
            
            // 3. 删除患者记录
            $sql = "DELETE FROM patients WHERE id = $patient_id";
            $conn->query($sql);
            
            // 4. 如果存在关联用户，删除用户记录
            if ($user_id) {
                $sql = "DELETE FROM users WHERE id = $user_id";
                $conn->query($sql);
                
                // 5. 删除系统日志
                $sql = "DELETE FROM system_logs WHERE user_id = $user_id";
                $conn->query($sql);
            }
            
            // 记录操作日志
            logAction($_SESSION['user_id'], '删除患者（ID：' . $patient_id . '）');
            
            // 提交事务
            $conn->commit();
            
            $success = '患者删除成功！';
        } else {
            $error = '患者不存在';
            $conn->rollback();
        }
    } catch (Exception $e) {
        // 回滚事务
        $conn->rollback();
        $error = '删除患者失败：' . $e->getMessage();
    }
}

// 处理查看患者详情请求
$view_patient = null;
if (isset($_GET['view']) && is_numeric($_GET['view'])) {
    $patient_id = (int)$_GET['view'];
    $sql = "SELECT p.*, u.username, u.email, u.last_login 
            FROM patients p 
            LEFT JOIN users u ON p.user_id = u.id 
            WHERE p.id = $patient_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $view_patient = $result->fetch_assoc();
        
        // 获取患者的预约记录
        $appointments = [];
        $app_sql = "SELECT a.*, d.name as doctor_name, dep.name as department_name 
                   FROM appointments a 
                   LEFT JOIN doctors d ON a.doctor_id = d.id 
                   LEFT JOIN departments dep ON d.department_id = dep.id 
                   WHERE a.patient_id = $patient_id 
                   ORDER BY a.appointment_date DESC, a.appointment_time DESC";
        $app_result = $conn->query($app_sql);
        if ($app_result && $app_result->num_rows > 0) {
            while ($app = $app_result->fetch_assoc()) {
                $appointments[] = $app;
            }
        }
        
        // 获取患者的医疗记录
        $records = [];
        $rec_sql = "SELECT m.*, d.name as doctor_name 
                   FROM medical_records m 
                   LEFT JOIN doctors d ON m.doctor_id = d.id 
                   WHERE m.patient_id = $patient_id 
                   ORDER BY m.created_at DESC";
        $rec_result = $conn->query($rec_sql);
        if ($rec_result && $rec_result->num_rows > 0) {
            while ($rec = $rec_result->fetch_assoc()) {
                $records[] = $rec;
            }
        }
    }
}

// 处理编辑患者表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_patient']) && is_numeric($_POST['patient_id'])) {
    $patient_id = (int)$_POST['patient_id'];
    $name = $_POST['name'] ?? '';
    $gender = $_POST['gender'] ?? '';
    $birthdate = $_POST['birthdate'] ?? '';
    $id_card = $_POST['id_card'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $address = $_POST['address'] ?? '';
    $emergency_contact = $_POST['emergency_contact'] ?? '';
    $emergency_phone = $_POST['emergency_phone'] ?? '';
    $blood_type = $_POST['blood_type'] ?? '';
    $height = $_POST['height'] ? (float)$_POST['height'] : null;
    $weight = $_POST['weight'] ? (float)$_POST['weight'] : null;
    $medical_history = $_POST['medical_history'] ?? '';
    $allergies = $_POST['allergies'] ?? '';
    $chronic_diseases = $_POST['chronic_diseases'] ?? '';
    $notes = $_POST['notes'] ?? '';
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    
    // 基本验证
    if (empty($name) || empty($gender) || empty($birthdate) || empty($id_card) || empty($phone)) {
        $error = '请填写所有必填字段';
    } else if (!preg_match('/^\d{17}[\dXx]$/', $id_card)) {
        $error = '请输入有效的身份证号';
    } else if (!preg_match('/^1\d{10}$/', $phone)) {
        $error = '请输入有效的手机号码';
    } else {
        // 检查身份证号是否已被其他患者使用
        $check_sql = "SELECT id FROM patients WHERE id_card = '$id_card' AND id != $patient_id";
        $check_result = $conn->query($check_sql);
        if ($check_result && $check_result->num_rows > 0) {
            $error = '该身份证号已存在';
        } else {
            // 开始事务
            $conn->begin_transaction();
            
            try {
                // 转义字符串值
                $name = $conn->real_escape_string($name);
                $gender = $conn->real_escape_string($gender);
                $id_card = $conn->real_escape_string($id_card);
                $phone = $conn->real_escape_string($phone);
                $address = $conn->real_escape_string($address);
                $emergency_contact = $conn->real_escape_string($emergency_contact);
                $emergency_phone = $conn->real_escape_string($emergency_phone);
                $blood_type = $conn->real_escape_string($blood_type);
                $medical_history = $conn->real_escape_string($medical_history);
                $allergies = $conn->real_escape_string($allergies);
                $chronic_diseases = $conn->real_escape_string($chronic_diseases);
                $notes = $conn->real_escape_string($notes);
                
                // 更新患者信息
                $update_sql = "UPDATE patients SET 
                               name = '$name',
                               gender = '$gender',
                               birthdate = '$birthdate',
                               id_card = '$id_card',
                               phone = '$phone',
                               address = '$address',
                               emergency_contact = '$emergency_contact',
                               emergency_phone = '$emergency_phone',
                               blood_type = '$blood_type',
                               height = " . ($height ? $height : "NULL") . ",
                               weight = " . ($weight ? $weight : "NULL") . ",
                               medical_history = '$medical_history',
                               allergies = '$allergies',
                               chronic_diseases = '$chronic_diseases',
                               notes = '$notes',
                               updated_at = NOW()
                               WHERE id = $patient_id";
                
                if (!$conn->query($update_sql)) {
                    throw new Exception('更新患者信息失败：' . $conn->error);
                }
                
                // 如果提供了用户信息，更新用户表
                if (!empty($username) || !empty($email)) {
                    // 获取患者的用户ID
                    $user_sql = "SELECT user_id FROM patients WHERE id = $patient_id";
                    $user_result = $conn->query($user_sql);
                    
                    if ($user_result && $user_result->num_rows > 0) {
                        $user_id = $user_result->fetch_assoc()['user_id'];
                        
                        if ($user_id) {
                            $updates = [];
                            
                            if (!empty($username)) {
                                // 检查用户名是否已被其他用户使用
                                $check_user_sql = "SELECT id FROM users WHERE username = '$username' AND id != $user_id";
                                $check_user_result = $conn->query($check_user_sql);
                                if ($check_user_result && $check_user_result->num_rows > 0) {
                                    throw new Exception('用户名已存在');
                                }
                                
                                $username = $conn->real_escape_string($username);
                                $updates[] = "username = '$username'";
                            }
                            
                            if (!empty($email)) {
                                // 检查邮箱是否已被其他用户使用
                                $check_email_sql = "SELECT id FROM users WHERE email = '$email' AND id != $user_id";
                                $check_email_result = $conn->query($check_email_sql);
                                if ($check_email_result && $check_email_result->num_rows > 0) {
                                    throw new Exception('邮箱已存在');
                                }
                                
                                $email = $conn->real_escape_string($email);
                                $updates[] = "email = '$email'";
                            }
                            
                            if (!empty($updates)) {
                                $update_user_sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = $user_id";
                                if (!$conn->query($update_user_sql)) {
                                    throw new Exception('更新用户信息失败：' . $conn->error);
                                }
                            }
                        }
                    }
                }
                
                // 记录操作日志
                logAction($_SESSION['user_id'], '更新患者信息（ID：' . $patient_id . '）');
                
                // 提交事务
                $conn->commit();
                
                $success = '患者信息已更新！';
            } catch (Exception $e) {
                // 回滚事务
                $conn->rollback();
                $error = $e->getMessage();
            }
        }
    }
}

// 处理添加患者表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_patient'])) {
    $name = $_POST['name'] ?? '';
    $gender = $_POST['gender'] ?? '';
    $birthdate = $_POST['birthdate'] ?? '';
    $id_card = $_POST['id_card'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $address = $_POST['address'] ?? '';
    $emergency_contact = $_POST['emergency_contact'] ?? '';
    $emergency_phone = $_POST['emergency_phone'] ?? '';
    $blood_type = $_POST['blood_type'] ?? '';
    $height = $_POST['height'] ? (float)$_POST['height'] : null;
    $weight = $_POST['weight'] ? (float)$_POST['weight'] : null;
    $medical_history = $_POST['medical_history'] ?? '';
    $allergies = $_POST['allergies'] ?? '';
    $chronic_diseases = $_POST['chronic_diseases'] ?? '';
    $notes = $_POST['notes'] ?? '';
    $create_account = isset($_POST['create_account']) && $_POST['create_account'] == '1';
    
    // 基本验证
    if (empty($name) || empty($gender) || empty($birthdate) || empty($id_card) || empty($phone)) {
        $error = '请填写所有必填字段';
    } else if (!preg_match('/^\d{17}[\dXx]$/', $id_card)) {
        $error = '请输入有效的身份证号';
    } else if (!preg_match('/^1\d{10}$/', $phone)) {
        $error = '请输入有效的手机号码';
    } else {
        // 检查身份证号是否已存在
        $check_sql = "SELECT id FROM patients WHERE id_card = '$id_card'";
        $check_result = $conn->query($check_sql);
        if ($check_result && $check_result->num_rows > 0) {
            $error = '该身份证号已存在';
        } else {
            // 开始事务
            $conn->begin_transaction();
            
            try {
                $user_id = null;
                
                // 如果需要创建账号
                if ($create_account) {
                    $username = $_POST['username'] ?? '';
                    $email = $_POST['email'] ?? '';
                    $password = $_POST['password'] ?? '123456'; // 默认密码
                    
                    // 检查用户名是否已存在
                    if (!empty($username)) {
                        $check_user_sql = "SELECT id FROM users WHERE username = '$username'";
                        $check_user_result = $conn->query($check_user_sql);
                        if ($check_user_result && $check_user_result->num_rows > 0) {
                            throw new Exception('用户名已存在');
                        }
                    } else {
                        // 自动生成用户名（使用手机号后4位）
                        $username = 'patient_' . substr($phone, -4) . rand(100, 999);
                    }
                    
                    // 检查邮箱是否已存在
                    if (!empty($email)) {
                        $check_email_sql = "SELECT id FROM users WHERE email = '$email'";
                        $check_email_result = $conn->query($check_email_sql);
                        if ($check_email_result && $check_email_result->num_rows > 0) {
                            throw new Exception('邮箱已存在');
                        }
                    }
                    
                    // 创建用户账号
                    $hashed_password = md5($password); // 生产环境应使用更安全的方法
                    $insert_user_sql = "INSERT INTO users (username, password, email, role, created_at) 
                                       VALUES ('$username', '$hashed_password', '$email', 'patient', NOW())";
                    
                    if (!$conn->query($insert_user_sql)) {
                        throw new Exception('创建用户账号失败：' . $conn->error);
                    }
                    
                    $user_id = $conn->insert_id;
                }
                
                // 转义字符串值
                $name = $conn->real_escape_string($name);
                $gender = $conn->real_escape_string($gender);
                $id_card = $conn->real_escape_string($id_card);
                $phone = $conn->real_escape_string($phone);
                $address = $conn->real_escape_string($address);
                $emergency_contact = $conn->real_escape_string($emergency_contact);
                $emergency_phone = $conn->real_escape_string($emergency_phone);
                $blood_type = $conn->real_escape_string($blood_type);
                $medical_history = $conn->real_escape_string($medical_history);
                $allergies = $conn->real_escape_string($allergies);
                $chronic_diseases = $conn->real_escape_string($chronic_diseases);
                $notes = $conn->real_escape_string($notes);
                
                // 插入患者记录
                $insert_sql = "INSERT INTO patients (name, gender, birthdate, id_card, phone, address, 
                                                    emergency_contact, emergency_phone, blood_type, 
                                                    height, weight, medical_history, allergies, 
                                                    chronic_diseases, notes, user_id, created_at) 
                              VALUES ('$name', '$gender', '$birthdate', '$id_card', '$phone', '$address', 
                                     '$emergency_contact', '$emergency_phone', '$blood_type', 
                                     " . ($height ? $height : "NULL") . ", 
                                     " . ($weight ? $weight : "NULL") . ", 
                                     '$medical_history', '$allergies', '$chronic_diseases', '$notes', 
                                     " . ($user_id ? $user_id : "NULL") . ", NOW())";
                
                if (!$conn->query($insert_sql)) {
                    throw new Exception('添加患者失败：' . $conn->error);
                }
                
                // 记录操作日志
                logAction($_SESSION['user_id'], '添加患者（姓名：' . $name . '）');
                
                // 提交事务
                $conn->commit();
                
                $success = '患者添加成功！';
            } catch (Exception $e) {
                // 回滚事务
                $conn->rollback();
                $error = $e->getMessage();
            }
        }
    }
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>患者管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/all_3b858821.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 px-0 admin-sidebar">
                <div class="py-3 px-3 bg-dark">
                    <a href="<?php echo SITE_URL; ?>admin/" class="text-white text-decoration-none">
                        <i class="fas fa-hospital-alt mr-2"></i>管理后台
                    </a>
                </div>
                <div class="p-3">
                    <div class="text-white mb-3">
                        <i class="fas fa-user-circle mr-1"></i> <?php echo $_SESSION['username']; ?>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/">
                                <i class="fas fa-tachometer-alt mr-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/users.php">
                                <i class="fas fa-users mr-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="<?php echo SITE_URL; ?>admin/patients.php">
                                <i class="fas fa-user-injured mr-2"></i>患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/doctors.php">
                                <i class="fas fa-user-md mr-2"></i>医生管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/departments.php">
                                <i class="fas fa-hospital mr-2"></i>科室管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/appointments.php">
                                <i class="fas fa-calendar-check mr-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/medicines.php">
                                <i class="fas fa-pills mr-2"></i>药品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/records.php">
                                <i class="fas fa-notes-medical mr-2"></i>病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/logs.php">
                                <i class="fas fa-history mr-2"></i>系统日志
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/settings.php">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>">
                                <i class="fas fa-home mr-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>logout.php">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10 ml-sm-auto px-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">患者管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addPatientModal">
                            <i class="fas fa-plus mr-1"></i> 添加患者
                        </button>
                    </div>
                </div>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 患者列表 -->
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h5 class="mb-0">患者列表</h5>
                            </div>
                            <div class="col-auto">
                                <div class="input-group">
                                    <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="搜索患者...">
                                    <div class="input-group-append">
                                        <button class="btn btn-sm btn-outline-secondary" type="button" id="searchButton">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover table-striped" id="patientTable">
                                <thead>
                                    <tr>
                                        <th onclick="sortTable(0)">ID <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(1)">姓名 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(2)">性别 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(3)">年龄 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(4)">联系电话 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(5)">身份证号 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th onclick="sortTable(6)">注册时间 <i class="fas fa-sort text-muted ml-1"></i></th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($patients)): ?>
                                        <tr>
                                            <td colspan="8" class="text-center">暂无患者</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($patients as $patient): ?>
                                            <?php 
                                            // 计算年龄
                                            $age = '';
                                            if (!empty($patient['birthdate'])) {
                                                $birthdate = new DateTime($patient['birthdate']);
                                                $today = new DateTime('today');
                                                $age = $birthdate->diff($today)->y;
                                            }
                                            
                                            // 脱敏处理
                                            $masked_phone = !empty($patient['phone']) ? substr_replace($patient['phone'], '****', 3, 4) : '';
                                            $masked_id_card = !empty($patient['id_card']) ? substr_replace($patient['id_card'], '************', 3, 12) : '';
                                            ?>
                                            <tr>
                                                <td><?php echo $patient['id']; ?></td>
                                                <td><?php echo htmlspecialchars($patient['name']); ?></td>
                                                <td><?php echo htmlspecialchars($patient['gender']); ?></td>
                                                <td><?php echo $age; ?></td>
                                                <td><?php echo $masked_phone; ?></td>
                                                <td><?php echo $masked_id_card; ?></td>
                                                <td><?php echo date('Y-m-d H:i', strtotime($patient['created_at'])); ?></td>
                                                <td>
                                                    <a href="?edit=<?php echo $patient['id']; ?>" class="btn btn-sm btn-info" title="编辑患者">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="?view=<?php echo $patient['id']; ?>" class="btn btn-sm btn-success" title="查看详情">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    <a href="?delete=<?php echo $patient['id']; ?>" class="btn btn-sm btn-danger" title="删除患者" onclick="return confirm('确定要删除此患者吗？此操作不可恢复！');">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        <div class="row align-items-center">
                            <div class="col">
                                <small class="text-muted">共 <?php echo $total_records; ?> 个患者，当前显示第 <?php echo $page; ?> 页，共 <?php echo $total_pages; ?> 页</small>
                            </div>
                            <div class="col-auto">
                                <nav aria-label="Page navigation">
                                    <ul class="pagination pagination-sm mb-0">
                                        <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo isset($_GET['edit']) ? '&edit='.$_GET['edit'] : ''; ?>">上一页</a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
                                        <?php endif; ?>
                                        
                                        <?php
                                        // 显示分页链接
                                        $start_page = max(1, $page - 2);
                                        $end_page = min($total_pages, $page + 2);
                                        
                                        // 总是显示第一页链接
                                        if ($start_page > 1) {
                                            echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                                            if ($start_page > 2) {
                                                echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                            }
                                        }
                                        
                                        // 显示当前页面的前后几页
                                        for ($i = $start_page; $i <= $end_page; $i++) {
                                            if ($i == $page) {
                                                echo '<li class="page-item active"><a class="page-link" href="#">' . $i . '</a></li>';
                                            } else {
                                                echo '<li class="page-item"><a class="page-link" href="?page=' . $i . '">' . $i . '</a></li>';
                                            }
                                        }
                                        
                                        // 总是显示最后一页链接
                                        if ($end_page < $total_pages) {
                                            if ($end_page < $total_pages - 1) {
                                                echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                            }
                                            echo '<li class="page-item"><a class="page-link" href="?page=' . $total_pages . '">' . $total_pages . '</a></li>';
                                        }
                                        ?>
                                        
                                        <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo isset($_GET['edit']) ? '&edit='.$_GET['edit'] : ''; ?>">下一页</a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled"><a class="page-link" href="#">下一页</a></li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 患者详情模态框 -->
                <?php if ($view_patient): ?>
                <div class="modal fade" id="viewPatientModal" tabindex="-1" role="dialog" aria-hidden="true" data-show="true">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">患者详情</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <ul class="nav nav-tabs" id="patientTab" role="tablist">
                                    <li class="nav-item">
                                        <a class="nav-link active" id="info-tab" data-toggle="tab" href="#info" role="tab">基本信息</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" id="appointments-tab" data-toggle="tab" href="#appointments" role="tab">预约记录</a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" id="records-tab" data-toggle="tab" href="#records" role="tab">医疗记录</a>
                                    </li>
                                </ul>
                                <div class="tab-content p-3" id="patientTabContent">
                                    <!-- 基本信息 -->
                                    <div class="tab-pane fade show active" id="info" role="tabpanel">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6 class="text-primary">个人信息</h6>
                                                <div class="table-responsive">
                                                    <table class="table table-sm">
                                                        <tr>
                                                            <th width="35%">ID</th>
                                                            <td><?php echo $view_patient['id']; ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>姓名</th>
                                                            <td><?php echo htmlspecialchars($view_patient['name']); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>性别</th>
                                                            <td><?php echo htmlspecialchars($view_patient['gender']); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>出生日期</th>
                                                            <td><?php echo $view_patient['birthdate']; ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>身份证号</th>
                                                            <td><?php echo $view_patient['id_card']; ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>联系电话</th>
                                                            <td><?php echo $view_patient['phone']; ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>紧急联系人</th>
                                                            <td><?php echo htmlspecialchars($view_patient['emergency_contact'] ?? ''); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>紧急联系电话</th>
                                                            <td><?php echo $view_patient['emergency_phone'] ?? ''; ?></td>
                                                        </tr>
                                                    </table>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <h6 class="text-primary">账号信息</h6>
                                                <div class="table-responsive">
                                                    <table class="table table-sm">
                                                        <tr>
                                                            <th width="35%">用户名</th>
                                                            <td><?php echo htmlspecialchars($view_patient['username'] ?? '未绑定'); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>邮箱</th>
                                                            <td><?php echo htmlspecialchars($view_patient['email'] ?? ''); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>注册时间</th>
                                                            <td><?php echo $view_patient['created_at'] ? date('Y-m-d H:i', strtotime($view_patient['created_at'])) : ''; ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>最后登录</th>
                                                            <td><?php echo $view_patient['last_login'] ? date('Y-m-d H:i', strtotime($view_patient['last_login'])) : '从未登录'; ?></td>
                                                        </tr>
                                                    </table>
                                                </div>
                                                
                                                <h6 class="text-primary mt-4">医疗信息</h6>
                                                <div class="table-responsive">
                                                    <table class="table table-sm">
                                                        <tr>
                                                            <th width="35%">血型</th>
                                                            <td><?php echo htmlspecialchars($view_patient['blood_type'] ?? ''); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>过敏史</th>
                                                            <td><?php echo htmlspecialchars($view_patient['allergies'] ?? ''); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>慢性病</th>
                                                            <td><?php echo htmlspecialchars($view_patient['chronic_diseases'] ?? ''); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>备注</th>
                                                            <td><?php echo htmlspecialchars($view_patient['notes'] ?? ''); ?></td>
                                                        </tr>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- 预约记录 -->
                                    <div class="tab-pane fade" id="appointments" role="tabpanel">
                                        <?php if (empty($appointments)): ?>
                                            <div class="alert alert-info">暂无预约记录</div>
                                        <?php else: ?>
                                            <div class="table-responsive">
                                                <table class="table table-sm table-hover">
                                                    <thead>
                                                        <tr>
                                                            <th>ID</th>
                                                            <th>预约日期</th>
                                                            <th>预约时间</th>
                                                            <th>科室</th>
                                                            <th>医生</th>
                                                            <th>状态</th>
                                                            <th>创建时间</th>
                                                            <th>操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($appointments as $app): ?>
                                                            <tr>
                                                                <td><?php echo $app['id']; ?></td>
                                                                <td><?php echo $app['appointment_date']; ?></td>
                                                                <td><?php echo substr($app['appointment_time'], 0, 5); ?></td>
                                                                <td><?php echo htmlspecialchars($app['department_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($app['doctor_name']); ?></td>
                                                                <td>
                                                                    <?php
                                                                    switch ($app['status']) {
                                                                        case 'pending':
                                                                            echo '<span class="badge badge-warning">待确认</span>';
                                                                            break;
                                                                        case 'confirmed':
                                                                            echo '<span class="badge badge-primary">已确认</span>';
                                                                            break;
                                                                        case 'completed':
                                                                            echo '<span class="badge badge-success">已完成</span>';
                                                                            break;
                                                                        case 'cancelled':
                                                                            echo '<span class="badge badge-danger">已取消</span>';
                                                                            break;
                                                                        default:
                                                                            echo '<span class="badge badge-secondary">未知</span>';
                                                                    }
                                                                    ?>
                                                                </td>
                                                                <td><?php echo date('Y-m-d H:i', strtotime($app['created_at'])); ?></td>
                                                                <td>
                                                                    <a href="appointments.php?edit=<?php echo $app['id']; ?>" class="btn btn-sm btn-info" title="编辑预约">
                                                                        <i class="fas fa-edit"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- 医疗记录 -->
                                    <div class="tab-pane fade" id="records" role="tabpanel">
                                        <?php if (empty($records)): ?>
                                            <div class="alert alert-info">暂无医疗记录</div>
                                        <?php else: ?>
                                            <div class="table-responsive">
                                                <table class="table table-sm table-hover">
                                                    <thead>
                                                        <tr>
                                                            <th>ID</th>
                                                            <th>就诊日期</th>
                                                            <th>主诉</th>
                                                            <th>医生</th>
                                                            <th>诊断</th>
                                                            <th>操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($records as $rec): ?>
                                                            <tr>
                                                                <td><?php echo $rec['id']; ?></td>
                                                                <td><?php echo date('Y-m-d', strtotime($rec['created_at'])); ?></td>
                                                                <td><?php echo htmlspecialchars(mb_substr($rec['symptoms'], 0, 20)) . (mb_strlen($rec['symptoms']) > 20 ? '...' : ''); ?></td>
                                                                <td><?php echo htmlspecialchars($rec['doctor_name']); ?></td>
                                                                <td><?php echo htmlspecialchars(mb_substr($rec['diagnosis'], 0, 20)) . (mb_strlen($rec['diagnosis']) > 20 ? '...' : ''); ?></td>
                                                                <td>
                                                                    <a href="records.php?view=<?php echo $rec['id']; ?>" class="btn btn-sm btn-info" title="查看详情">
                                                                        <i class="fas fa-eye"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <a href="?edit=<?php echo $view_patient['id']; ?>" class="btn btn-primary">编辑患者</a>
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
                <script>
                    $(document).ready(function() {
                        $('#viewPatientModal').modal('show');
                    });
                </script>
                <?php endif; ?>
                
                <!-- 添加患者模态框 -->
                <div class="modal fade" id="addPatientModal" tabindex="-1" role="dialog" aria-labelledby="addPatientModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="addPatientModalLabel">添加患者</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <form method="post">
                                <div class="modal-body">
                                    <ul class="nav nav-tabs" id="addPatientTab" role="tablist">
                                        <li class="nav-item">
                                            <a class="nav-link active" id="add-personal-tab" data-toggle="tab" href="#add-personal" role="tab">个人信息</a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" id="add-medical-tab" data-toggle="tab" href="#add-medical" role="tab">医疗信息</a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" id="add-account-tab" data-toggle="tab" href="#add-account" role="tab">账号信息</a>
                                        </li>
                                    </ul>
                                    <div class="tab-content p-3" id="addPatientTabContent">
                                        <!-- 个人信息 -->
                                        <div class="tab-pane fade show active" id="add-personal" role="tabpanel">
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="name">姓名 <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="name" name="name" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="gender">性别 <span class="text-danger">*</span></label>
                                                    <select class="form-control" id="gender" name="gender" required>
                                                        <option value="">请选择</option>
                                                        <option value="男">男</option>
                                                        <option value="女">女</option>
                                                        <option value="其他">其他</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="birthdate">出生日期 <span class="text-danger">*</span></label>
                                                    <input type="date" class="form-control" id="birthdate" name="birthdate" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="id_card">身份证号 <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="id_card" name="id_card" required>
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="phone">联系电话 <span class="text-danger">*</span></label>
                                                    <input type="tel" class="form-control" id="phone" name="phone" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="address">住址</label>
                                                    <input type="text" class="form-control" id="address" name="address">
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="emergency_contact">紧急联系人</label>
                                                    <input type="text" class="form-control" id="emergency_contact" name="emergency_contact">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="emergency_phone">紧急联系电话</label>
                                                    <input type="tel" class="form-control" id="emergency_phone" name="emergency_phone">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- 医疗信息 -->
                                        <div class="tab-pane fade" id="add-medical" role="tabpanel">
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="blood_type">血型</label>
                                                    <input type="text" class="form-control" id="blood_type" name="blood_type">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="height">身高</label>
                                                    <input type="text" class="form-control" id="height" name="height">
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="weight">体重</label>
                                                    <input type="text" class="form-control" id="weight" name="weight">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="medical_history">病史</label>
                                                    <textarea class="form-control" id="medical_history" name="medical_history"></textarea>
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="allergies">过敏史</label>
                                                    <textarea class="form-control" id="allergies" name="allergies"></textarea>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="chronic_diseases">慢性病</label>
                                                    <textarea class="form-control" id="chronic_diseases" name="chronic_diseases"></textarea>
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="notes">备注</label>
                                                    <textarea class="form-control" id="notes" name="notes"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- 账号信息 -->
                                        <div class="tab-pane fade" id="add-account" role="tabpanel">
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="username">用户名</label>
                                                    <input type="text" class="form-control" id="username" name="username">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="email">邮箱</label>
                                                    <input type="email" class="form-control" id="email" name="email">
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group col-md-6">
                                                    <label for="password">密码</label>
                                                    <input type="password" class="form-control" id="password" name="password">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="create_account">创建账号</label>
                                                    <input type="checkbox" class="form-control" id="create_account" name="create_account">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="submit" class="btn btn-primary">添加患者</button>
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- 版权信息 -->
                <footer class="mt-5 text-center text-muted">
                    <p>
                        &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. 版权所有
                        <br>
                        <small>Powered by <a href="#" class="text-muted">州弟学安全</a> | 版本 <?php echo VERSION; ?></small>
                    </p>
                </footer>
            </div>
        </div>
    </div>

    <script src="/assets\js/jquery-3_7b53a2dc.5.1.min.js"></script></script></script></script>
    <script src="/assets\js/popper_9c21e708.min.js"></script></script></script></script>
    <script src="/assets\js/bootstrap_a618e9ff.min.js"></script></script></script></script>
    <script src="/assets\js/main.js"></script></script>
    <script>
        // 表格排序函数
        function sortTable(n) {
            // 在客户端临时排序当前页的数据
            var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById("patientTable");
            switching = true;
            dir = "asc";
            
            while (switching) {
                switching = false;
                rows = table.rows;
                
                for (i = 1; i < (rows.length - 1); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("TD")[n];
                    y = rows[i + 1].getElementsByTagName("TD")[n];
                    
                    if (dir == "asc") {
                        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    } else if (dir == "desc") {
                        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                
                if (shouldSwitch) {
                    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                    switching = true;
                    switchcount++;
                } else {
                    if (switchcount == 0 && dir == "asc") {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }
        
        // 表格搜索功能
        $(document).ready(function(){
            // 实时搜索（当前页过滤）
            $("#searchInput").on("keyup", function() {
                var value = $(this).val().toLowerCase();
                $("#patientTable tbody tr").filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                });
            });
            
            // 搜索按钮点击事件
            $("#searchButton").on("click", function() {
                var value = $("#searchInput").val().toLowerCase();
                $("#patientTable tbody tr").filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                });
            });
        });
    </script>
</body>
</html> 